#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
from datetime import datetime, date
from functools import singledispatch


# import json
# from datetime import datetime, date
#
# class CJsonEncoder(json.JSONEncoder):
#     def default(self, obj):
#         if isinstance(obj, datetime):
#             return obj.strftime('%Y-%m-%d %H:%M:%S')
#         elif isinstance(obj, date):
#             return obj.strftime("%Y-%m-%d")
#         else:
#             return json.JSONEncoder.default(self, obj)
#
# json.dumps(blog,cls=CJsonEncoder)

class ExtendJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        try:
            return convert(obj)
        except TypeError:
            return super(ExtendJSONEncoder, self).default(obj)


@singledispatch
def convert(o):
    if hasattr(o, '__dict__') and o.__dict__:
        return o.__dict__
    else:
        raise TypeError('can not convert type')


@convert.register(datetime)
def _(o):
    return o.strftime('%Y-%m-%d %H:%M:%S')


@convert.register(date)
def _(o):
    return o.strftime("%Y-%m-%d")


def to_json(str):
    return json.loads(str.decode('utf-8'))


def to_json_str(obj):
    # return json.dumps(obj, cls=CJsonEncoder).encode('utf-8')
    return json.dumps(obj, cls=ExtendJSONEncoder).encode('utf-8')
